package com.yjy.fuyao.ucenter.api;

import com.yjy.fuyao.ucenter.service.MailService;
import com.yjy.fuyao.utils.result.R;
import com.yjy.fuyao.utils.util.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/ucenter/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/send/{mail}")
    public R send(@PathVariable String mail){
        if(StringUtils.isEmpty(mail)){
            return R.ok().message("邮箱不能为空");
        }
        String code = RandomUtils.getFourBitRandom();
        boolean result = mailService.send(mail, code);
        System.out.println("==========send:result:"+result+"==============");
        if(result){
            boolean res = redisTemplate.opsForValue().setIfAbsent("fuyao:mail:code:"+mail,code,5, TimeUnit.MINUTES);
            if(!res){
                return R.error().message("请勿短期重复发送验证码");
            }
        }else{
            return R.error().message("邮件发送失败");
        }
        return R.ok();
    }

}
